package com.uvlab.sitespot.service.fdb;

import com.uvlab.sitespot.service.node.JxNode;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class JxAppFdbService{

    private List<JxNode> nodeList;
    private LinkedHashMap nodeHashMap=new LinkedHashMap();
    RestTemplate restTemplate;
    private  String url="http://localhost:8080";
    public JxAppFdbService(){

    }

    public void init(String url){
        this.url=url;
    }
    public LinkedHashMap getNodeList() {
        restTemplate= new RestTemplate();
        nodeHashMap= restTemplate.getForObject(url+"/node", LinkedHashMap.class);
        return  this.nodeHashMap;
    }

    public  LinkedHashMap getNodeList(String user,String beg,String end){
        restTemplate= new RestTemplate();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("user", user);
        map.add("begtime",beg);
        map.add("endtime",end);
        String urll=String.format(url+"/node/filter?user=%s&begtime=%s&endtime=%s",user,beg,end);
        return restTemplate.getForObject(urll,LinkedHashMap.class);
    }

    //templerate version, need node as parm in the future
    public String add(String name,String user,String time) {
        restTemplate= new RestTemplate();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("name", name);
        map.add("user",user);
        map.add("updtime",time);

        return restTemplate.postForObject(url+"/node",map,String.class,map);
    }

    public String add(JxNode node) {
        restTemplate= new RestTemplate();
        return  restTemplate.postForObject(url+"/node",node,String.class);
    }

    public JxNode getById(String id){
        restTemplate=new RestTemplate();
        return restTemplate.getForObject(url+"/node/"+id,JxNode.class);
    }

    public JxNode updateById(JxNode node){
        restTemplate=new RestTemplate();
        String id=node.getUuid().toString();
        restTemplate.put(url+"/node/"+id,node);
        return  node;
    }

    public void deleteById(String id){
        restTemplate=new RestTemplate();
        restTemplate.delete(url+"/node/"+id);
    }


    public String addById(String name,String user,String time,String id) {
        restTemplate= new RestTemplate();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("name",name);
        map.add("user",user);
        map.add("updtime",time);
        String urll=url+"/node/"+id+"/children";
        return restTemplate.postForObject(urll,map,String.class,map);
    }

    public LinkedHashMap getChildren(String id){
        restTemplate= new RestTemplate();
        return restTemplate.getForObject(url+"/node/"+id+"/children",LinkedHashMap.class);
    }
    public String addById(JxNode node,String id) {

        restTemplate= new RestTemplate();
        String urll=url+"/node/"+id+"/children";
        return restTemplate.postForObject(urll,node,String.class);
    }

    public void uploadFile(String name, MultipartFile file) {
        //region RestTemplate method,not supported chinese
        //solve chinese name can't be recognized
        restTemplate= new RestTemplate();
        Charset charset=Charset.forName("UTF-8");
        StringHttpMessageConverter stringHttpMessageConverter=new StringHttpMessageConverter(charset);
        List<HttpMessageConverter<?>> messageConverters=restTemplate.getMessageConverters();
        messageConverters.set(1,stringHttpMessageConverter);
        restTemplate.setMessageConverters(messageConverters);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        final String filename="somefile.txt";
        map.add("name", name);
        map.add("filename", filename);
        ByteArrayResource contentsAsResource = null;
        try {
            contentsAsResource = new ByteArrayResource(file.getBytes()){
                @Override
                public String getFilename(){
                    return filename;
                }
            };
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.add("file", contentsAsResource);
        restTemplate.postForObject(url+"/File",map,String.class,map);
        //endregion


        //region HttpClient Method
        /*
        String BOUNDARY="-----WebKitFormBoundaryHV2ymHFg03ehbqgZ";
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url+"/File");
        try {
            URL urlx = new URL(url+"/File");
            HttpURLConnection connection = (HttpURLConnection) urlx.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            String itemBoundary = "\r\n--"+BOUNDARY+"\r\n";
            String endBoundary="\r\n--"+BOUNDARY+"--\r\n";
            OutputStream out = connection.getOutputStream();
            out.write(itemBoundary.getBytes());
            String postHeader1=String.format("Content-Disposition:form-data;name=\"file\";filename=\"%s\"\r\nContent-Type:application/octet-stream\r\n\r\n",file.getOriginalFilename());
            String postHeader2="Content-Disposition:form-data;name=\"name\"\r\n\r\n";
            out.write(postHeader1.getBytes());
            out.write(file.getBytes());
            out.write(itemBoundary.getBytes());
            out.write(postHeader2.getBytes());
            out.write(name.getBytes());
            out.write(endBoundary.getBytes());
            out.flush();
            out.close();
            connection.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        */
        //endregion

    }

    public ResponseEntity<byte[]> downloadFile() {
        restTemplate= new RestTemplate();
        return restTemplate.getForEntity(url+"/down",byte[].class);
    }

    public ResponseEntity<byte[]> downloadFile(String filename,String day) {
        restTemplate= new RestTemplate();
        String urlx=url+"/down"+String.format("?filename=%s&day=%s",filename,day);
        ResponseEntity<byte[]> ret;
        // ret=restTemplate.getForEntity(url,byte[].class);
        return  restTemplate.getForEntity(urlx,byte[].class);
    }
}
